import React from "react";
import { connect } from "dva";
import { message, Checkbox, Button, Tabs, List, Card, Col, Row, Modal, Spin } from "antd";
import KnowledgeCheckBox from "@/pages/robotManagement/knowledgeCheckBox";
import styles from "./index.less";
import UserSession from "@/UserSession";
import { getRootCategoryInfo } from '@/services/knowledgeFile';
import { formatMessage } from 'umi-plugin-react/locale';

class KnowledgeConfiguration extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			knowledgeList: [],
			atlasList: [],
			dialogList: [],
			fileList: [],
			checkedKnowledgeIds: [],
			checkedAtlasIds: [],
			checkedDialogIds: [],
			checkedFileIds: [],
			knowledgeIndeterminate: false,
			atlasIndeterminate: false,
			dialogIndeterminate: false,
			fileIndeterminate: false,
			checkAllForKnowledge: false,
			checkAllForAtlas: false,
			checkAllForDialog: false,
			checkAllForFile: false,
			configurationType: "knowledge",
			saveLoading: false,
			showAddKnowledge: false,
			robotCategoryListQuery: {
				current: 1,
				size: 12,
			},
			activeKey: 1,
			selectCategoryId: "",
			knowledgeType: [],
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
	}

	info = item => {
		this.getDataInfo(item.id, (res) => {
			if (res && res.type && res.type.length > 0) {
				let type = res ? res.type : [];
				this.setState({
					showAddKnowledge: true,
					selectCategoryId: item.id,
					knowledgeType: type,
					configurationType: type && type.length > 0 ? type[0] === 'qa' ? 'knowledge' : type[0] === 'graph' ? 'atlas' : type[0] : '',
				}, () => {
					console.log(type);
					if (type && type.length > 0) {
						switch (type[0]) {
							case "qa":
								this.getListForKnowledge();
								break;
							case "graph":
								this.getListForAtlas();
								break;
							case "dialog":
								this.getListForDialog();
								break;
							case "file":
								this.getListForFile();
								break;
						}
					} else {
						this.getListForKnowledge();
					}
				})
			} else {
				message.info('当前知识库，暂无知识点')
			}
		});
	}

	getDataInfo = async (id, callback) => {
		let res = await getRootCategoryInfo({ id });
		console.log(res);
		callback(res);
	}

	//获取分类信息
	getKnowledgeList = () => {
		const { configurationType } = this.state;
		switch (configurationType) {
			case "knowledge":
				this.getListForKnowledge();
				break;
			case "atlas":
				this.getListForAtlas();
				break;
			case "dialog":
				this.getListForDialog();
				break;
			case "file":
				this.getListForFile();
				break;
		}
	};

	/**
	 * 获取知识点分类信息
	 */
	getListForKnowledge = () => {
		const { dispatch, applicationId } = this.props;
		const { activeKey, selectCategoryId } = this.state;
		dispatch({
			type: "knowledgeConfiguration/fetchKnowledgeList",
			payload: {
				applicationId,
				categoryId: selectCategoryId,
				urlPrefix: activeKey == 2 ? 1 : null,
			},
			callback: (res) => {
				let checkedKnowledgeIds = [];
				// 知识点递归获取选中的知识点id
				function getChildren(data) {
					data.map((item) => {
						// console.log(item);
						if (item.children) {
							getChildren(item.children);
						};
						if (item.check) {
							checkedKnowledgeIds.push(item.id);
						}
					});
				};

				if (res.length) {
					getChildren(res);
				};

				this.setState({
					knowledgeList: res,
					checkedKnowledgeIds,
					knowledgeIndeterminate: checkedKnowledgeIds.length > 0 && checkedKnowledgeIds.length < res.length,
					checkAllForKnowledge: checkedKnowledgeIds.length === res.length && res.length != 0,
				});
			},
		});
	};

	/**
	 * 获取知识导图分类信息
	 */
	getListForAtlas = () => {
		const { dispatch, applicationId } = this.props;
		const { selectCategoryId, activeKey } = this.state;
		dispatch({
			type: "knowledgeConfiguration/fetchAtlasList",
			payload: {
				applicationId,
				categoryId: selectCategoryId,
				urlPrefix: activeKey == 2 ? 1 : null,
			},
			callback: (res) => {
				let checkedAtlasIds = [];
				//图谱
				for (const item of res) {
					if (item.check) {
						checkedAtlasIds.push(item.id);
					}
				};

				this.setState({
					atlasList: res,
					checkedAtlasIds,
					atlasIndeterminate: checkedAtlasIds.length > 0 && checkedAtlasIds.length < res.length,
					checkAllForAtlas: checkedAtlasIds.length === res.length && res.length != 0,
				});
			},
		});
	};

	/**
	 * 获取多轮会话分类信息
	 */
	getListForDialog = () => {
		const { dispatch, applicationId } = this.props;
		const { selectCategoryId, activeKey } = this.state;
		dispatch({
			type: "knowledgeConfiguration/fetchDialogList",
			payload: {
				applicationId,
				categoryId: selectCategoryId,
				urlPrefix: activeKey == 2 ? 1 : null,
			},
			callback: (res) => {
				let checkedDialogIds = [];

				//多轮会话
				for (const item of res) {
					if (item.check) {
						checkedDialogIds.push(item.id);
					}
				};

				this.setState({
					dialogList: res,
					checkedDialogIds,
					dialogIndeterminate: checkedDialogIds.length > 0 && checkedDialogIds.length < res.length,
					checkAllForDialog: checkedDialogIds.length === res.length && res.length != 0,
				});
			},
		});
	};

	/**
	 * 获取文档知识点分类信息
	 */
	getListForFile = () => {
		const { dispatch, applicationId } = this.props;
		const { activeKey, selectCategoryId } = this.state;
		dispatch({
			type: "knowledgeConfiguration/fetchFileList",
			payload: {
				applicationId,
				categoryId: selectCategoryId,
				urlPrefix: activeKey == 2 ? 1 : null,
			},
			callback: (res) => {
				let checkedFileIds = [];
				// 知识点递归获取选中的知识点id
				function getChildren(data) {
					data.map((item) => {
						// console.log(item);
						if (item.children) {
							getChildren(item.children);
						}
						if (item.check) {
							checkedFileIds.push(item.id);
						}
					});
				}

				if (res.length) {
					getChildren(res);
				}

				this.setState({
					fileList: res,
					checkedFileIds,
					fileIndeterminate: checkedFileIds.length > 0 && checkedFileIds.length < res.length,
					checkAllForFile: checkedFileIds.length === res.length && res.length != 0,
				});
			},
		});
	}

	/**
	 * 知识点分类全选按钮change事件
	 * @param e
	 */
	onCheckAllChangeForKnowledge = (e) => {
		const { knowledgeList } = this.state;
		const knowledgeIdList = knowledgeList.map((item) => item.id);
		this.setState({
			checkedKnowledgeIds: e.target.checked ? knowledgeIdList : [],
			checkAllForKnowledge: e.target.checked,
			knowledgeIndeterminate: false,
		});
	};

	/**
	 * 图谱分类全选按钮change事件
	 * @param e
	 */
	onCheckAllChangeForAtlas = (e) => {
		const { atlasList } = this.state;
		const atlasIdList = atlasList.map((item) => item.id);
		this.setState({
			checkedAtlasIds: e.target.checked ? atlasIdList : [],
			checkAllForAtlas: e.target.checked,
			atlasIndeterminate: false,
		});
	};

	/**
	 * 多轮会话全选按钮change事件
	 * @param e
	 */
	onCheckAllChangeForDialog = (e) => {
		const { dialogList } = this.state;
		const dialogIdList = dialogList.map((item) => item.id);
		this.setState({
			checkedDialogIds: e.target.checked ? dialogIdList : [],
			checkAllForDialog: e.target.checked,
			dialogIndeterminate: false,
		});
	};

	/**
	 * 文档知识点全选按钮change事件
	 * @param e
	 */
	onCheckAllChangeForFile = (e) => {
		const { fileList } = this.state;
		const fileIdList = fileList.map((item) => item.id);
		this.setState({
			checkedFileIds: e.target.checked ? fileIdList : [],
			checkAllForFile: e.target.checked,
			fileIndeterminate: false,
		});
	};

	/**
	 * 知识点分类复选框change事件
	 * @param checkedList
	 */
	onChangeForKnowledge = (checkedList) => {
		const { knowledgeList } = this.state;
		const knowledgeIdList = knowledgeList.map((item) => item.id);
		this.setState({
			checkedKnowledgeIds: checkedList,
			knowledgeIndeterminate: !!checkedList.length && checkedList.length < knowledgeIdList.length,
			checkAllForKnowledge: checkedList.length === knowledgeIdList.length,
		});
	};

	/**
	 * 图谱分类复选框change事件
	 * @param checkedList
	 */
	onChangeForAtlas = (checkedList) => {
		const { atlasList } = this.state;
		const atlasIdList = atlasList.map((item) => item.id);
		this.setState({
			checkedAtlasIds: checkedList,
			atlasIndeterminate: !!checkedList.length && checkedList.length < atlasIdList.length,
			checkAllForAtlas: checkedList.length === atlasIdList.length,
		});
	};

	/**
	 * 多轮会话分类复选框change事件
	 * @param checkedList
	 */
	onChangeForDialog = (checkedList) => {
		const { dialogList } = this.state;
		const dialogIdList = dialogList.map((item) => item.id);
		this.setState({
			checkedDialogIds: checkedList,
			dialogIndeterminate: !!checkedList.length && checkedList.length < dialogIdList.length,
			checkAllForDialog: checkedList.length === dialogIdList.length,
		});
	};

	/**
	 * 文档知识点分类复选框change事件
	 * @param checkedList
	 */
	onChangeForFile = (checkedList) => {
		const { fileList } = this.state;
		const fileIdList = fileList.map((item) => item.id);
		this.setState({
			checkedFileIds: checkedList,
			fileIndeterminate: !!checkedList.length && checkedList.length < fileIdList.length,
			checkAllForFile: checkedList.length === fileIdList.length,
		});
	};

	/**
	 * 保存-loading
	 */
	onSave = () => {
		this.setState({ saveLoading: true }, () => {
			this.doSaveDispatch();
		});
	};

	/**
	 * 保存-请求
	 */
	doSaveDispatch = () => {
		const {
			checkedKnowledgeIds, checkedAtlasIds, checkedDialogIds,
			configurationType, activeKey, selectCategoryId, checkedFileIds,
		} = this.state;
		const { dispatch, applicationId } = this.props;
		let url = "";
		let obj = {};
		switch (configurationType) {
			case "knowledge":
				url = "knowledgeConfiguration/saveCheckedKnowledgeIds";
				obj.qaCategoryIds = checkedKnowledgeIds;
				break;
			case "atlas":
				url = "knowledgeConfiguration/saveCheckedAtlasIds";
				obj.atlasCategoryIds = checkedAtlasIds;
				break;
			case "dialog":
				url = "knowledgeConfiguration/saveCheckedDialogIds";
				obj.dialogCategoryIds = checkedDialogIds;
				break;
			case "file":
				url = "knowledgeConfiguration/saveCheckedFileIds";
				obj.docCategoryIds = checkedFileIds;
				break;
		};
		obj.sys = activeKey == 2;
		obj.applicationId = applicationId;
		obj.rootCategoryId = selectCategoryId;
		dispatch({
			type: url,
			payload: obj,
			callback: (res) => {
				this.setState({ saveLoading: false }, () => {
					if (!res.code) {
						message.info(res.message);
					};
					this.onCloseCancel();
					this.getKnowledgeList();
					this.props.getRobotCategoryList();
				});
			},
		});
	};

	/**
	 * 全选按钮的change事件
	 * @returns {*}
	 */
	onCheckAllChange = (e, type) => {
		const that = this;
		switch (type) {
			case "knowledge":
				that.onCheckAllChangeForKnowledge(e);
				break;
			case "atlas":
				that.onCheckAllChangeForAtlas(e);
				break;
			case "dialog":
				that.onCheckAllChangeForDialog(e);
				break;
			case "file":
				that.onCheckAllChangeForFile(e);
				break;
		}
	};

	/**
	 * 分类复选框按钮的change事件
	 * @returns {*}
	 */
	onCheckListChange = (checkedList, type) => {
		const that = this;
		switch (type) {
			case "knowledge":
				that.onChangeForKnowledge(checkedList);
				break;
			case "atlas":
				that.onChangeForAtlas(checkedList);
				break;
			case "dialog":
				that.onChangeForDialog(checkedList);
				break;
			case "file":
				that.onChangeForFile(checkedList);
				break;
		}
	};

	/**
	 * 切换tab
	 * @returns {*}
	 */
	changeTab = (key) => {
		this.setState({ configurationType: key }, () => {
			this.getKnowledgeList();
		});
	};

	onCloseCancel = () => {
		this.setState({
			showAddKnowledge: false,
			selectCategoryId: "",
			knowledgeList: [],
			atlasList: [],
			dialogList: [],
			configurationType: 'knowledge',
		})
	}

	render() {
		const {
			knowledgeList, knowledgeIndeterminate, checkAllForKnowledge, checkedKnowledgeIds, atlasList,
			atlasIndeterminate, checkedAtlasIds, checkAllForAtlas, dialogList, dialogIndeterminate,
			checkedDialogIds, checkAllForDialog, configurationType, saveLoading, showAddKnowledge,
			fileList, checkedFileIds, fileIndeterminate, checkAllForFile, knowledgeType,
		} = this.state;

		return (
			<Modal
				title={formatMessage({ id: 'knowledgeConfig.knowledgeConfiguration'})}
				visible={showAddKnowledge}
				width={800}
				onCancel={this.onCloseCancel}
				footer={null}
				bodyStyle={{ padding: 0 }}
				destroyOnClose
			>
				<Tabs
					tabPosition={"left"}
					activeKey={configurationType}
					onChange={key => this.changeTab(key)}
					className={styles.knowledgeTab}
				>
					{knowledgeType.indexOf("qa") > -1 ? (
						<Tabs.TabPane tab='问答知识点' key='knowledge' style={{ textAlign: "left" }}>
							<KnowledgeCheckBox
								title={"问答知识点"}
								indeterminate={knowledgeIndeterminate}
								list={knowledgeList}
								checkData={checkedKnowledgeIds}
								checkAllData={checkAllForKnowledge}
								onCheckAllChange={this.onCheckAllChange}
								onCheckListChange={this.onCheckListChange}
								type={"knowledge"}
							/>
							<div className={styles.knowledgeTabBtn}>
								<Button type={"primary"} onClick={this.onSave} loading={saveLoading}>{formatMessage({ id: 'knowledgeConfig.documentSave'})}</Button>
							</div>
						</Tabs.TabPane>
					) : null}
					{knowledgeType.indexOf("graph") > -1 && UserSession.hasAtlasKnowledge() ? (
						<Tabs.TabPane tab='知识导图' key='atlas' style={{ textAlign: "left" }}>
							<KnowledgeCheckBox
								title={"知识导图"}
								indeterminate={atlasIndeterminate}
								list={atlasList}
								checkData={checkedAtlasIds}
								checkAllData={checkAllForAtlas}
								onCheckAllChange={this.onCheckAllChange}
								onCheckListChange={this.onCheckListChange}
								type={"atlas"}
							/>
							<div className={styles.knowledgeTabBtn}>
								<Button type={"primary"} onClick={this.onSave} loading={saveLoading}>{formatMessage({ id: 'knowledgeConfig.documentSave'})}</Button>
							</div>
						</Tabs.TabPane>
					) : null}
					{knowledgeType.indexOf("dialog") > -1 && UserSession.hasAtlasKnowledge() ? (
						<Tabs.TabPane tab='多轮对话' key='dialog'>
							<KnowledgeCheckBox
								title={"多轮对话"}
								indeterminate={dialogIndeterminate}
								list={dialogList}
								checkData={checkedDialogIds}
								checkAllData={checkAllForDialog}
								onCheckAllChange={this.onCheckAllChange}
								onCheckListChange={this.onCheckListChange}
								type={"dialog"}
							/>
							<div className={styles.knowledgeTabBtn}>
								<Button type={"primary"} onClick={this.onSave} loading={saveLoading}>{formatMessage({ id: 'knowledgeConfig.documentSave'})}</Button>
							</div>
						</Tabs.TabPane>
					) : null}
					{knowledgeType.indexOf("file") > -1 ? (
						<Tabs.TabPane tab={formatMessage({ id: 'knowledgeConfig.documentKnowledge' })} key='file'>
							<KnowledgeCheckBox
								title={formatMessage({ id: 'knowledgeConfig.documentKnowledge' })}
								indeterminate={fileIndeterminate}
								list={fileList}
								checkData={checkedFileIds}
								checkAllData={checkAllForFile}
								onCheckAllChange={this.onCheckAllChange}
								onCheckListChange={this.onCheckListChange}
								type={"file"}
							/>
							<div className={styles.knowledgeTabBtn}>
								<Button type={"primary"} onClick={this.onSave} loading={saveLoading}>{formatMessage({ id: 'knowledgeConfig.documentSave'})}</Button>
							</div>
						</Tabs.TabPane>
					) : null}
				</Tabs>
			</Modal>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(KnowledgeConfiguration);
